package com.rachel.studyapp.mvp.model;

import com.rachel.studyapp.entries.UserInfo;
import com.rachel.studyapp.mvp.ContractUtils;

import org.litepal.crud.DataSupport;

import java.util.List;

/**
 * Created by zhengshaorui on 2017/8/29.
 */

public class MineModel {
    private ContractUtils.IMinePresent mListener;

    public MineModel(ContractUtils.IMinePresent listener) {
        mListener = listener;
    }

    /**
     * 登陆
     */
    public void login(final UserInfo userInfo){
       if (isUsernameExit(userInfo.getUsername())){
           if (isUserExit(userInfo)) {
               new Thread(new Runnable() {
                   @Override
                   public void run() {
                       try {
                           mListener.showloading();
                           Thread.sleep(2000);
                       } catch (InterruptedException e) {
                           e.printStackTrace();
                       }
                       mListener.hideloading();
                       mListener.loginSuccess(userInfo);
                   }
               }).start();

           }else{
              mListener.loginFailure("密码错误!!!");
           }
       }else{
           mListener.loginFailure("未找到该账号，请核对信息");
       }
    }

    /**
     * 注册
     */
    public void register(final UserInfo userInfo){
        //判断一下是否已经注册过了,username不可以一样，password可以一样

       if (isUsernameExit(userInfo.getUsername())){
            mListener.registerFailure("账号已经被注册过了");

       }else{
           userInfo.save();
           new Thread(new Runnable() {
               @Override
               public void run() {
                   try {
                       mListener.showloading();
                       Thread.sleep(2000); //模拟提交数据
                   } catch (InterruptedException e) {
                       e.printStackTrace();
                   }
                   mListener.hideloading();
                   mListener.registerSuccess(userInfo);
               }
           }).start();



       }
    }

    private boolean isUsernameExit(String username){
        List<UserInfo> infos = DataSupport.where("username = ?",username).find(UserInfo.class);
        if (infos.isEmpty()){
            return false;
        }else{
            return true;
        }
    }
    private boolean isUserExit(UserInfo userInfo){
        List<UserInfo> infos = DataSupport.where("username = ? and password = ?",
               userInfo.getUsername(),userInfo.getPassword()).find(UserInfo.class);
        if (infos.isEmpty()){
            return false;
        }else{
            return true;
        }
    }
}
